//
//  XQCourseVideoViewController.swift
//  XiaoQiQiaoSwift
//
//  Created by tech-lab on 2016/12/1.
//  Copyright © 2016年 校企桥. All rights reserved.
//
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
import SwiftyJSON
import UIKit

class XQCourseVideoViewController: XQBaseViewController,UITableViewDataSource,UITableViewDelegate {

    var type = String()
    var cid = String()
    
    private  var tableView = UITableView()
    private var tableHeaderView = XQCourseVideoTableHeaderView()
    
    private var section_array = [JSON]()
    private var video_dic = [String:JSON]()
    
    private var sectionTitleArray = [String]()
    private var courseCommentMode:XQCourseVideoCommentMode?
    
    private var isChapter = Bool()
    private var XQCourseVideoCommentTableViewCellID = "XQCourseVideoCommentTableViewCellID"
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.isNavigationBarHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.isNavigationBarHidden = false
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    
    override func setRootView() {
        
        tableHeaderView = XQCourseVideoTableHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 290))
        tableHeaderView.backButton.addTarget(self, action: #selector(self.backLeft), for: .touchUpInside)
        self.view.addSubview(tableHeaderView)
        
        self.tableView = UITableView.init(frame:  CGRect.zero, style: .plain)
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.showsVerticalScrollIndicator = false
        self.view.addSubview(self.tableView)
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
        tableView.register(XQCourseVideoCommentTableViewCell.self, forCellReuseIdentifier: XQCourseVideoCommentTableViewCellID)
        tableView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view.snp.left)
            make.right.equalTo(self.view.snp.right)
            make.top.equalTo(tableHeaderView.snp.bottom).offset(5)
            make.bottom.equalTo(self.view.snp.bottom)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.requestcourseChapter), name: NSNotification.Name(rawValue: "courseChapter"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.requestcourseComment), name: NSNotification.Name(rawValue: "courseComment"), object: nil)
        requestcourseChapter()
    }
    

    

    func requestcourseChapter(){
        isChapter = true
        
        let urlstr = MTBaseURL.appending("NewVerCourse/courseChapter.json")
        let para:Parameters = ["cid":cid,"uid":"","type":type]
        Alamofire.request(urlstr ,parameters:para).responseJSON { (response) in
            let result = JSON.init(data: response.data!)
            let content = result["content"]
            
            self.video_dic = content["video"].dictionaryValue ;
            
            self.section_array = content["section"].arrayValue
            
            for dic:JSON in self.section_array{
                self.sectionTitleArray.append(dic["title"].stringValue)
            }
            
            if self.section_array.count != 0 && self.video_dic.count != 0 {
                let secid = self.section_array[0]["id"].stringValue
                if self.video_dic.count != 0{
                    let vidid =  self.video_dic[secid]?[0]["id"].stringValue
                    self.requestvideoShow(vid: vidid!)
                }
                
            }
            self.tableView.tableHeaderView = nil
            self.tableView.reloadData()
        }
        
    }
    
    
    func requestvideoShow(vid:String)  {
        let urlstr = MTBaseURL.appending("NewVerCourse/videoShow.json")
        let para:Parameters = ["vid":vid,"uid":"","type":type]
       
        Alamofire.request(urlstr ,parameters:para).responseJSON { (response) in
            let result = JSON.init(data: response.data!)
            let swf_url = result["content"]["swf_url"].stringValue;
            
        self.tableHeaderView.videoView.loadRequest(NSURLRequest.init(url: URL.init(string: swf_url)!) as URLRequest)
            
        }

    }
    
    // MARK: - Table view data source
    
     func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        if isChapter == true {
            return section_array.count
        }else{
            return 1
        }
        
    }
    
     func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        var sectionTitleArray = [String]()
        for dic:JSON in self.section_array{
            sectionTitleArray.append(dic["title"].stringValue)
        }
        if isChapter == true {
            return sectionTitleArray[section]
        }else{
            return ""
        }
    }
    
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
      
        if isChapter == true {
            let dic = section_array[section] as JSON
            let idd = dic["id"].stringValue
            let array = video_dic[idd]
            return (array?.count)!
        }else{
            return (self.courseCommentMode?.main?.count)!
        }
        
    }
    
     func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if isChapter == true {
            return 30
        }else{
            return 5
        }
    }
     func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if isChapter == true {
            return 40
        }else{
            var rowheight = 0
            
            let commentMode = self.courseCommentMode?.main?[indexPath.row]
            let size = commentMode?.content?.boundingRect(with:
                CGSize.init(width: SCREEN_WIDTH-30, height: CGFloat.greatestFiniteMagnitude), options: [NSStringDrawingOptions.usesFontLeading,NSStringDrawingOptions.usesLineFragmentOrigin], attributes: nil, context: nil);
            if (size?.height)! > 40 {
                rowheight = Int((size?.height)!)+20+80
            }else{
                rowheight = 40 + 60
            }
            return CGFloat(rowheight)
        }
    }
    
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if isChapter == true {
            let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
            // Configure the cell...
            cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
            let dic = section_array[indexPath.section] as JSON
            let idd = dic["id"].stringValue
            let array = video_dic[idd]
            cell.textLabel?.text = array?[indexPath.row]["video_name"].stringValue
            return cell
        }else{
            let commentCell = tableView.dequeueReusableCell(withIdentifier: XQCourseVideoCommentTableViewCellID) as!XQCourseVideoCommentTableViewCell
            commentCell.commentMode = self.courseCommentMode?.main?[indexPath.row]
            commentCell.sortLabel.text = "\(indexPath.row+1)楼"
            return commentCell
        
        }
    }
    

    func requestcourseComment(){
        isChapter = false
        
        let urlstr = MTBaseURL.appending("NewVerCourse/courseComment.json")
        let para:Parameters = ["cid":cid]
        Alamofire.request(urlstr ,parameters:para).responseObject { (response:DataResponse<XQCourseVideoCommentMode>) in
            self.courseCommentMode = response.result.value
            
            self.tableView.tableHeaderView = self.replyView()
            self.tableView.reloadData()
        }
        
    }

    func replyView() -> UIView {
       
        let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 100))
        let  textView = UITextView.init(frame: CGRect.init(x: 10, y: 5, width: SCREEN_WIDTH-20, height: 60))
        textView.text = "请输入评论内容"
        textView.layer.borderWidth = 1
        textView.layer.borderColor = UIColor.lightGray.cgColor
        headerView.addSubview(textView)
        
        let button = UIButton.init(frame: CGRect.zero)
        button.setTitle("发表评论", for: .normal)
        button.backgroundColor = UIColor.blue
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        headerView.addSubview(button)
        
        button.snp.makeConstraints { (make) in
            make.top.equalTo(textView.snp.bottom).offset(5)
            make.right.equalTo(textView.snp.right).offset(-10)
        }
        
        return headerView
        
    }
    
    
}
